// api_client.dart
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:http_interceptor/http_interceptor.dart';
import 'package:request_ruoyi/store/user_info.dart';

/// 统一追加 baseUrl & 打印参数
class BasePathInterceptor implements InterceptorContract {
  final String baseUrl;

  BasePathInterceptor(this.baseUrl);

  @override
  Future<BaseRequest> interceptRequest({required BaseRequest request}) async {
    debugPrint('\n-\n 请求拦截器---------------------------------');
    if (request is Request) {
      // 1. 追加完整路径
      final oldUrl = baseUrl + request.url.path;
      //设置请求的格式（在dart,中所有的后端请求地址，
      //需要设置为Uri类型，字符串地址不会被识别）
      late final Uri newUrl;
      // request.copyWith(url: newUrl);

      if (request.method == 'GET' && request.url.query.isNotEmpty) {
        debugPrint('请求参数：${request.url.query}');
        newUrl = Uri.parse(
          oldUrl,
        ).replace(queryParameters: request.url.queryParameters);
      } else {
        newUrl = Uri.parse(oldUrl);
        debugPrint('请求地址$newUrl');
      }

      if (UserInfo().token != null) {
        request.headers.addAll({
          'Authorization': 'Bearer ${UserInfo().token}',
          'isToken': 'true',
        });
      } else {
        request.headers.addAll({'isToken': 'false'});
      }

      //添加请求头
      final newHeaders = Map<String, String>.from(request.headers)
        ..['Accept'] =
            'application/json' // 设置默认接受 JSON 响应
        ..['Content-Type'] = 'application/json'; // 设置发送内容类型

      // 创建新的请求对象，包含新的 URL 和头部信息
      final newRequest = Request(request.method, newUrl)
        ..headers.addAll(newHeaders)
        ..body = request.body;

      // 2. 打印请求信息

      debugPrint('时间： ${DateTime.now()}');
      debugPrint('请求方法 ${newRequest.method}--请求URL:  $oldUrl');
      debugPrint('请求头 : ${newRequest.headers}');
      debugPrint('请求体：: ${newRequest.body}');
      debugPrint(' ----------------请求拦截器--结束请求321321321 \n-\n');

      //返回新的请求对象
      return newRequest;
    }
    return request;
  }

  @override
  Future<BaseResponse> interceptResponse({
    required BaseResponse response,
  }) async => response;

  @override
  FutureOr<bool> shouldInterceptRequest() {
    return true;
  }

  @override
  FutureOr<bool> shouldInterceptResponse() {
    return true;
  }
}

/// 全局客户端
final apiClient = InterceptedClient.build(
  interceptors: [BasePathInterceptor('http://172.16.1.7:8080')],
);


  //使用方法
  // final res = await apiClient.get(Uri.parse('/captcha'));
  // 实际发出的请求：GET https://172.16.1.7:8080/api/captcha